﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using GuessTheWordsEditor.Model;
using Microsoft.Win32;
using System.IO;
using GuessTheWordsEditor.Entity;

namespace GuessTheWordsEditor
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        //32px*32px
        static int unit = 32;

        WordInfoModelCollection hWordCollection;
        WordInfoModelCollection vWordCollection;
        List<WordInfoModel> allWordsList;
        List<CharLocationInfo> charLoctionList;

        public MainWindow()
        {
            InitializeComponent();
            this.WindowStartupLocation = System.Windows.WindowStartupLocation.CenterScreen;
            this.Loaded += new RoutedEventHandler(MainWindow_Loaded);
            this.Closing += new System.ComponentModel.CancelEventHandler(MainWindow_Closing);

        }

        void MainWindow_Closing(object sender, System.ComponentModel.CancelEventArgs e)
        {
            if (MessageBox.Show("是否退出工具？", "警告", MessageBoxButton.YesNo) == MessageBoxResult.No)
            {
                e.Cancel = true;
            }
        }

        void MainWindow_Loaded(object sender, RoutedEventArgs e)
        {
            this.Loaded -= new RoutedEventHandler(MainWindow_Loaded);
            this.canvas1.MouseRightButtonDown += new MouseButtonEventHandler(canvas1_MouseRightButtonDown);
            this.canvas1.MouseLeftButtonDown += new MouseButtonEventHandler(canvas1_MouseLeftButtonDown);

            this.btnHAdd.Click += new RoutedEventHandler(btnHAdd_Click);
            this.btnVAdd.Click += new RoutedEventHandler(btnVAdd_Click);
            this.btnLoadWordInfos.Click += new RoutedEventHandler(btnLoadWordInfos_Click);
            this.btnClear.Click += new RoutedEventHandler(btnClear_Click);
            this.btnExportMap.Click += new RoutedEventHandler(btnExportMap_Click);

            //背景线
            DrawBackgroundLine();

            hWordCollection = new WordInfoModelCollection();
            vWordCollection = new WordInfoModelCollection();
            allWordsList = new List<WordInfoModel>();
            charLoctionList = new List<CharLocationInfo>();

            gridHWords.DataContext = hWordCollection;
            gridVWords.DataContext = vWordCollection;
        }

        void btnExportMap_Click(object sender, RoutedEventArgs e)
        {
            //导出地图文件
            SaveFileDialog saveFileDialog = new SaveFileDialog();
            saveFileDialog.Filter = " map files(*.map)|*.map";
            saveFileDialog.Title = "保存map";
            saveFileDialog.AddExtension = true;
            saveFileDialog.RestoreDirectory = true;
            if (saveFileDialog.ShowDialog() == true)
            {
                //保存文件
                using (StreamWriter sw = new StreamWriter(saveFileDialog.FileName, false, Encoding.UTF8))
                {
                    //Count
                    sw.WriteLine(allWordsList.Count().ToString());
                    string wordSpiliter = "--";
                    string locationSpiliter = ",";
                    //word
                    StringBuilder sb = new StringBuilder();
                    foreach (var item in allWordsList)
                    {
                        sb.Clear();
                        sb.Append(item.Pinyin);
                        sb.Append(wordSpiliter);
                        sb.Append(item.Result);
                        sb.Append(wordSpiliter);
                        sb.Append(item.Describe);
                        sw.WriteLine(sb.ToString());
                    }

                    //location
                    foreach (var item in charLoctionList)
                    {
                        sb.Clear();
                        sb.Append(item.Row.ToString());
                        sb.Append(locationSpiliter);
                        sb.Append(item.Column.ToString());
                        sb.Append(locationSpiliter);
                        sb.Append(item.OrientationWordIndex >= 0 ? item.OrientationWordIndex.ToString() : "N");
                        sb.Append(locationSpiliter);
                        sb.Append(item.OrientationCharIndex >= 0 ? item.OrientationCharIndex.ToString() : "N");
                        sb.Append(locationSpiliter);
                        sb.Append(item.VerticalWordIndex >= 0 ? item.VerticalWordIndex.ToString() : "N");
                        sb.Append(locationSpiliter);
                        sb.Append(item.VerticalCharIndex >= 0 ? item.VerticalCharIndex.ToString() : "N");
                        sw.WriteLine(sb.ToString());
                    }
                    sw.Flush();
                }

                MessageBox.Show("保存成功", "恭喜");
            }
        }

        void btnClear_Click(object sender, RoutedEventArgs e)
        {
            if (MessageBox.Show("确定要清空吗?", "警告", MessageBoxButton.YesNo) == MessageBoxResult.Yes)
            {
                //清空Matrix
                charLoctionList.Clear();
                canvas1.Children.Clear();
                DrawBackgroundLine();

                foreach (var item in hWordCollection)
                {
                    item.Status = string.Empty;
                }
                foreach (var item in vWordCollection)
                {
                    item.Status = string.Empty;
                }
            }
        }

        void btnLoadWordInfos_Click(object sender, RoutedEventArgs e)
        {
            //载入词条
            OpenFileDialog openFile = new OpenFileDialog();
            if (openFile.ShowDialog() == true)
            {
                hWordCollection.Clear();
                vWordCollection.Clear();
                allWordsList.Clear();
                String file = openFile.FileName;
                using (StreamReader sr = new StreamReader(file))
                {
                    string line = sr.ReadLine();
                    while (!string.IsNullOrEmpty(line))
                    {
                        string[] components = line.Split('-');
                        if (components.Length == 4)
                        {
                            //0: 0-横向 1-竖向
                            //1: 答案
                            //2: 拼音
                            //3：描述
                            WordInfoModel model = new WordInfoModel();
                            model.Result = components[1];
                            model.Pinyin = components[2];
                            model.Describe = components[3];

                            allWordsList.Add(model);

                            if (components[0] == "0")
                            {
                                //横向 
                                hWordCollection.Add(model);
                            }
                            else if (components[0] == "1")
                            {
                                //竖向
                                vWordCollection.Add(model);
                            }
                            else
                            {
                                MessageBox.Show("方向标识错误");
                                return;
                            }
                        }
                        else
                        {
                            MessageBox.Show("存在格式错误，请检查");
                            return;
                        }

                        line = sr.ReadLine();
                    }
                }
            }
        }

        void btnVAdd_Click(object sender, RoutedEventArgs e)
        {
            WordEditorWindow win = new WordEditorWindow();
            if (win.ShowDialog() == true)
            {
                vWordCollection.Add(win.WordModel);
                allWordsList.Add(win.WordModel);
            }
        }

        void btnHAdd_Click(object sender, RoutedEventArgs e)
        {
            WordEditorWindow win = new WordEditorWindow();
            if (win.ShowDialog() == true)
            {
                hWordCollection.Add(win.WordModel);
                allWordsList.Add(win.WordModel);
            }
        }

        void canvas1_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            //左键
            int row = GetRowIndex(e.GetPosition(this.canvas1).Y);
            int column = GetColumnIndex(e.GetPosition(this.canvas1).X);

            if (chkHorizon.IsChecked.Value)
            {
                if (gridHWords.SelectedIndex >= 0)
                {
                    WordInfoModel model = (WordInfoModel)gridHWords.SelectedItem;
                    if (model != null)
                    {
                        UpdateMatrix(model, true, row, column);
                    }
                }
            }
            else
            {
                if (gridVWords.SelectedIndex >= 0)
                {
                    WordInfoModel model = (WordInfoModel)gridVWords.SelectedItem;
                    if (model != null)
                    {
                        UpdateMatrix(model, false, row, column);
                    }
                }
            }
        }

        private void UpdateMatrix(WordInfoModel word, bool isHorizon, int startRow, int startColumn)
        {
            int wordCount = word.Result.Length;
            if (isHorizon)
            {
                for (int column = startColumn; column < startColumn + wordCount; column++)
                {
                    if (column >= 10)
                    {
                        break;
                    }
                    //填进去
                    Border border = new Border();
                    border.Background = Brushes.White;
                    border.BorderThickness = new Thickness(1);
                    border.BorderBrush = Brushes.Black;
                    border.Width = unit;
                    border.Height = unit;
                    TextBlock txtChar = new TextBlock();
                    txtChar.Text = Convert.ToString(word.Result[column - startColumn]);
                    txtChar.FontSize = 18;
                    txtChar.HorizontalAlignment = System.Windows.HorizontalAlignment.Center;
                    txtChar.VerticalAlignment = System.Windows.VerticalAlignment.Center;
                    txtChar.Background = Brushes.White;
                    border.Child = txtChar;
                    Canvas.SetTop(border, startRow * unit);
                    Canvas.SetLeft(border, column * unit);
                    canvas1.Children.Add(border);

                    //存入记录
                    CharLocationInfo location = null;
                    foreach (var item in charLoctionList)
                    {
                        if (item.Row == startRow && item.Column == column)
                        {
                            location = item;
                        }
                    }
                    if (location == null)
                    {
                        location = new CharLocationInfo();
                        location.Row = startRow;
                        location.Column = column;
                        charLoctionList.Add(location);
                    }
                    location.OrientationWordIndex = allWordsList.IndexOf(word);
                    location.OrientationCharIndex = column - startColumn;

                    //border
                    location.charBorder = border;

                    word.Status = "已使用";

                }
            }
            else
            {
                for (int row = startRow; row < startRow + wordCount; row++)
                {
                    if (row >= 10)
                    {
                        break;
                    }
                    //填进去
                    Border border = new Border();
                    border.Background = Brushes.White;
                    border.BorderThickness = new Thickness(1);
                    border.BorderBrush = Brushes.Black;
                    border.Width = unit;
                    border.Height = unit;
                    TextBlock txtChar = new TextBlock();
                    txtChar.Text = Convert.ToString(word.Result[row - startRow]);
                    txtChar.FontSize = 18;
                    txtChar.HorizontalAlignment = System.Windows.HorizontalAlignment.Center;
                    txtChar.VerticalAlignment = System.Windows.VerticalAlignment.Center;
                    txtChar.Background = Brushes.White;
                    border.Child = txtChar;
                    Canvas.SetTop(border, row * unit);
                    Canvas.SetLeft(border, startColumn * unit);
                    canvas1.Children.Add(border);

                    //存入记录
                    CharLocationInfo location = null;
                    foreach (var item in charLoctionList)
                    {
                        if (item.Row == row && item.Column == startColumn)
                        {
                            location = item;
                        }
                    }
                    if (location == null)
                    {
                        location = new CharLocationInfo();
                        location.Row = row;
                        location.Column = startColumn;
                        charLoctionList.Add(location);
                    }
                    location.VerticalWordIndex = allWordsList.IndexOf(word);
                    location.VerticalCharIndex = row - startRow;

                    //border
                    location.charBorder = border;

                    word.Status = "已使用";
                }
            }

        }

        void canvas1_MouseRightButtonDown(object sender, MouseButtonEventArgs e)
        {
            //右键
            int row = GetRowIndex(e.GetPosition(this.canvas1).Y);
            int column = GetColumnIndex(e.GetPosition(this.canvas1).X);

            CharLocationInfo deleteOne = null;
            foreach (var item in charLoctionList)
            {
                if (item.Column == column && item.Row == row)
                {
                    deleteOne = item;
                    break;
                }
            }
            if (deleteOne != null)
            {
                charLoctionList.Remove(deleteOne);
                //清除界面
                this.canvas1.Children.Remove(deleteOne.charBorder);
            }
        }

        private void DrawBackgroundLine()
        {
            //水平线
            for (int i = 1; i < 10; i++)
            {
                Line line = new Line();
                line.X1 = 0;
                line.X2 = unit * 10 - 1;
                line.Y1 = i * unit;
                line.Y2 = i * unit;
                line.Stroke = Brushes.Black;
                line.StrokeThickness = 1;
                canvas1.Children.Add(line);
            }

            //垂直线
            for (int i = 1; i < 10; i++)
            {
                Line line = new Line();
                line.Y1 = 0;
                line.Y2 = unit * 10 - 1;
                line.X1 = i * unit;
                line.X2 = i * unit;
                line.Stroke = Brushes.Black;
                line.StrokeThickness = 1;
                canvas1.Children.Add(line);
            }
        }

        private int GetRowIndex(double y)
        {
            return (int)(y / unit);
        }

        private int GetColumnIndex(double x)
        {
            return (int)(x / unit);
        }
    }
}
